import * as THREE from 'three'//导入three.js核心库
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' //导入轨道控制器
// import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'//导入GLTF模型加载器
class motor3d {
    constructor(selector) {    
        this.container = document.querySelector(selector)//获取容器
        this.scene
        this.camera 
        this.renderer
        this.controls
        this.init() //初始化
        this.animate()//循环函数
    }

    init() {
        // 初始化场景
        this.initScene()    
        // 初始化辅助轴
        this.initAxesHelper()
        // 初始化灯光
        this.initLight() 
        // 初始化相机
        this.initCamera()
        // 初始化渲染器
        this.initRender()
        // 初始化轨道控制器
        this.initControls()
        // 监听场景大小改变，重新渲染尺寸
        window.addEventListener('resize',this.onWindowResize.bind(this))
      }

      initScene() {
        this.scene = new THREE.Scene()

        const geometry = new THREE.BoxGeometry();
        const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        const cube = new THREE.Mesh(geometry, material);
        this.scene.add(cube);
        this.scene.background = new THREE.Color(0xa0a0a0)
    }

    initAxesHelper() {
        const axesHelper = new THREE.AxesHelper(5)
        this.scene.add(axesHelper)
      }

      initLight() {
        const hesLight = new THREE.HemisphereLight(0xffffff,0x444444)
        hesLight.intensity = 0.6
        this.scene.add(hesLight)
    
        const dirLight = new THREE.DirectionalLight()
        dirLight.position.set(5,5,5)
        this.scene.add(dirLight)    
    }
    initCamera() {
        this.camera = new THREE.PerspectiveCamera(75,(window.innerWidth-300) / window.innerHeight,0.1,100)
        this.camera.position.set(1.5,1.5,1.5)
    }

    initRender() {
        this.renderer = new THREE.WebGLRenderer({antialias:true})//设置抗锯齿
        //设置屏幕像素比
        this.renderer.setPixelRatio(window.devicePixelRatio)
        //渲染的尺寸大小
        this.renderer.setSize((window.innerWidth-300),window.innerHeight) 
        // 添加到容器
        this.container.appendChild(this.renderer.domElement)
      }


      render() {    
        this.renderer.render(this.scene,this.camera)
      }

      animate() { 
        this.renderer.setAnimationLoop(this.render.bind(this))
      }

      initControls() {
        this.controls = new OrbitControls(this.camera,this.renderer.domElement)
      }

      onWindowResize() {
        this.camera.aspect = ((window.innerWidth-300)) / window.innerHeight
        this.camera.updateProjectionMatrix()//更新矩阵，将3d内容投射到2d画面上转换
        this.renderer.setSize((window.innerWidth-300),window.innerHeight)
      }

} 

export default motor3d